package edu.purdue.touch;

import java.util.Enumeration;
import java.util.Hashtable;
import TUIO.TuioCursor;
import TUIO.TuioTime;

public class TouchEventHandler {
	
	public Status current_status;
	public Status previous_status;
	public boolean inside = false;
	private Hashtable<Long, TuioCursor> cursorList = new Hashtable<Long,TuioCursor>();
	
	public TouchEventHandler()
	{
		previous_status = Status.INITIAL;
		current_status =  Status.INITIAL;
		inside = false;
	}
	
	public void add(TuioCursor tcur) {
		cursorList.put(tcur.getSessionID(), tcur);
		
		previous_status = current_status;
		
		if(current_status == Status.INITIAL) {
			current_status = Status.HOVERING;
		}
		else if(current_status == Status.HOVERING) {
			current_status = Status.WAIT;
		}
		else if(current_status == Status.WAIT) {
			current_status = Status.ROTATE;
		}
	}
	
	public void remove(TuioCursor tcur) {
		cursorList.remove(tcur.getSessionID());
		
		previous_status = current_status;
		
		if (current_status == Status.HOVERING) {
			if (tcur.getDistance( tcur.getPath().firstElement() ) < 0.01) {				
				current_status = Status.TAP;
			}
			else {
				current_status = Status.INITIAL;
			}			
		}
		else if (current_status == Status.DRAG || current_status == Status.SELECT || current_status == Status.WAIT) {
			current_status = Status.HOVERING;
		}
		else if(current_status == Status.ROTATE) {
			current_status = Status.WAIT;
		}
	}
	
	public void update(TuioCursor tcur) {	
		// empty
	}
	
	public void refresh(TuioTime ttime) {
		//System.out.println( tcur.getDistance( tcur.getPath().firstElement() ) +"");
		// if distance is increasing go to state 3 else state 4
		
		if(cursorList.size() == 0) {
			previous_status = current_status ;
			current_status = Status.INITIAL;
		}
		
		if (current_status == Status.WAIT) {
			Enumeration<TuioCursor> enm = cursorList.elements();
			if(cursorList.size() == 2) {
				TuioCursor tcursor1 = enm.nextElement();
				TuioCursor tcursor2 = enm.nextElement();
				
				if (tcursor1.getPath().size() >= 3) {

					double theta1 = tcursor1.getAngle(tcursor1.getPath().firstElement());
					double theta2 = tcursor2.getAngle(tcursor2.getPath().firstElement());
					//System.out.println(tcursor1.getDistance(tcursor1.getPath().firstElement()));
					
					if (Math.abs(theta1 - theta2) > Math.PI/2) {
						previous_status = current_status ;
						current_status = Status.SELECT;						
					}
					
					else if ((tcursor1.getDistance(tcursor1.getPath().firstElement()) < 0.005) ||
							 (tcursor2.getDistance(tcursor2.getPath().firstElement()) < 0.005)) {
						previous_status = current_status ;
						current_status = Status.SELECT;	
					}
					else {
						previous_status = current_status ;
						current_status = Status.DRAG;
					}
				}				
			}			
		}
	}
}
